<template>
  <div class="farm-container">
    <nav-bar style="background-color: #0689f4; color: #fff">
      <div slot="center">扫一扫</div>
    </nav-bar>
    <div class="scan">
      <div id="bcid">
        <div style="height: 40%"></div>
        <p class="tip">...载入中...</p>
      </div>
      <footer class="footer">
        <!-- <button @click="startRecognize">1.开始扫描</button> -->
        <van-button @click="startRecognize" type="primary" block>开始扫描</van-button>
        <!-- <button @click="closeScan">4.结束扫描</button> -->
        <van-button @click="closeScan" type="primary" block style="margin-top: 30px;">结束扫描</van-button>
      </footer>
    </div>
  </div>
</template>

<script>
import NavBar from "../../../components/NavBar.vue";

// 扩展API加载完毕后调用onPlusReady回调函数
document.addEventListener( "plusready", onPlusReady, false );
// 扩展API加载完毕，现在可以正常调用扩展API
function onPlusReady() {
    var e = document.getElementById("scan");
    e.removeAttribute( "disabled" );
}
let scan = null;  

export default {
  name: "deviceQR",
  components: {
    NavBar,
  },
  props: {},
  data() {
    return {};
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    this.startRecognize();
  },
  destroyed() {
    this.cancelScan();
    this.closeScan();
  },
  methods: {
    // 创建扫描控件
    startRecognize() {
      let that = this;
      if (!window.plus) return;
      scan = new plus.barcode.Barcode("bcid");
      that.startScan();
      scan.onmarked = onmarked;
      function onmarked(type, result) {
        switch (type) {
          case plus.barcode.QR:
            type = "QR";
            break;
          case plus.barcode.EAN13:
            type = "EAN13";
            break;
          case plus.barcode.EAN8:
            type = "EAN8";
            break;
          default:
            type = "其它" + type;
            break;
        }
        console.log(result);
        that.$router.push({
          name: "checkList",
          params: {
            info:result
          },
        });
        that.closeScan();
      }
    },
    // 开始扫描
    startScan() {
      if (!window.plus) return;
      scan.start();
    },
    // 关闭扫描
    cancelScan() {
      if (!window.plus) return;
      scan.cancel();
    },
    // 关闭条码识别控件
    closeScan() {
      if (!window.plus) return;
      scan.close();
    },
  },
};
</script>

<style scoped lang="less">
.scan {
  height: 100%;
  #bcid {
    margin-top: 90px;
    width: 100%;
    height: 350px;
    text-align: center;
    color: #fff;
    background: #ccc;
  }
  .footer{
    margin-top: 60px;
    
  }
}
</style>